package com.tyk.bookstore.front.order.strategy.split;

import com.tyk.bookstore.front.common.core.model.exception.CustomException;
import com.tyk.bookstore.front.order.model.result.OrderResultEnum;
import com.tyk.bookstore.front.order.strategy.split.model.SplitDto;
import com.tyk.bookstore.front.order.strategy.split.model.SplitMode;
import com.tyk.bookstore.front.order.strategy.split.model.SplitStock;
import com.tyk.bookstore.front.order.util.MapStructOrder;
import com.tyk.bookstore.front.storage.service.StockApiService;
import com.tyk.bookstore.front.system.service.SystemSettingApiService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @author tyk
 * @description OrderSplitManager
 */
@Component
public class OrderSplitManager {
    private static Map<String, OrderSplitAction> map;

    private final SystemSettingApiService systemSettingApiService;

    private final StockApiService stockApiService;

    private final MapStructOrder mapStructOrder;


    public OrderSplitManager(Map<String, OrderSplitAction> map, SystemSettingApiService systemSettingApiService, StockApiService stockApiService, MapStructOrder mapStructOrder) {
        OrderSplitManager.map = map;
        this.systemSettingApiService = systemSettingApiService;
        this.stockApiService = stockApiService;
        this.mapStructOrder = mapStructOrder;
    }

    /**
     * 拆单
     *
     * @param consigneeAddressId 收货地址ID
     * @param splitStockList     各商品及数量
     * @return 拆单结果
     */
    public List<SplitDto> split(Long consigneeAddressId, List<SplitStock> splitStockList) {
        SplitMode mode = getOrderSplitMode();
        String actionName = StringUtils.uncapitalize(mode.getClazzName());
        return map.get(actionName).split(consigneeAddressId, splitStockList);
    }

    /**
     * 查单并扣减库存
     *
     * @param consigneeAddressId 收货地址ID
     * @param splitStockList     各商品及数量
     * @return 拆单结果
     */
    public List<SplitDto> splitThenDeduct(Long consigneeAddressId, List<SplitStock> splitStockList) {
        SplitMode mode = getOrderSplitMode();
        // 拆单
        String actionName = StringUtils.uncapitalize(mode.getClazzName());
        List<SplitDto> splitList = map.get(actionName).split(consigneeAddressId, splitStockList);
        // 扣减库存
        stockApiService.deduct(mapStructOrder.toStock4OrderDeductQueryList(splitList));
        // 返回拆单参数
        return splitList;
    }

    /**
     * 获取拆单模式
     *
     * @return 拆单模式
     */
    @NotNull
    private SplitMode getOrderSplitMode() {
        SplitMode mode;
        try {
            mode = SplitMode.valueOf(systemSettingApiService.getOrderSplitMode());
        } catch (IllegalArgumentException e) {
            throw new CustomException(OrderResultEnum.ORDER_SPLIT_MODE_UNSUPPORTED);
        }
        return mode;
    }
}
